package com.servlet; /**
 * @author wzm
 * @create 2023-03-13 15:28
 */

import com.entity.User;
import com.service.UserSerivce;
import com.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private UserSerivce userSerivce = new UserServiceImpl();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        //获取表单参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String remember = request.getParameter("remember");

        User login = userSerivce.login(new User(username, password));
        if(login != null){
            //成功
            //判断是否勾选记住
            if ("1".equals(remember)) {//勾选
                //将信息存储到Cookie中
                Cookie uname = new Cookie("username",username);
                Cookie pwd = new Cookie("password",password);

                //存储7天
                uname.setMaxAge(60*60*24*7);
                pwd.setMaxAge(60*60*24*7);

                response.addCookie(uname);
                response.addCookie(pwd);
            }

            //登录成功
            //将登录的用户存入Session方便在会话中使用Session
            request.getSession().setAttribute("loginUser",login);
            response.sendRedirect(request.getContextPath()+"/index.jsp");


        }else{
            //失败
            request.setAttribute("errorMsg","用户名或密码错误，请重试！");
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }


    }



}
